#include "spi.h"
#include "dma.h"

extern void  Delay(unsigned long  ulVal); 
extern uint8_t gDATABUF[DATA_BUF_SIZE]; 

/*********************************************************************//**

 ***********************************************************************/
void SSP_ReadBlock ( uint8_t  *data, uint16_t dlen)
{
	uint8_t *rdata8;
	uint16_t wlen;
    uint32_t tmp;
	wlen = dlen;
	/* Clear all remaining data in RX FIFO */
	while (SSPX->SR & SSP_SR_RNE){
		tmp = (uint32_t) SSP_ReceiveData(SSPX);
	}
	// Clear status
	SSPX->ICR = SSP_ICR_BITMASK;
	rdata8 = data;
	while ((dlen)||(wlen)){
		if ((SSPX->SR & SSP_SR_TNF)&&(wlen)){
			// Write data to buffer			
			SSP_SendData(SSPX, 0xFF);
			wlen--;
		}
		// Check for any data available in RX FIFO
		while ((SSPX->SR & SSP_SR_RNE)&&(dlen)){
			// Read data from SSP data
			tmp = SSP_ReceiveData(SSPX);
			// Store data to destination		
			*(rdata8) = (uint8_t) tmp;
			rdata8++;
			dlen --;
		}
	}
}


void SSP_WriteBlock ( uint8_t  *data,uint16_t dlen)
{
    uint8_t *wdata8;
	uint16_t rlen;
	rlen = dlen;
	/* Clear all remaining data in RX FIFO */
	while (SSPX->SR & SSP_SR_RNE){
		  SSP_ReceiveData(SSPX);
	}	
	// Clear status
	SSPX->ICR = SSP_ICR_BITMASK;
	wdata8 = (uint8_t *)data;
	
	while ((rlen)||(dlen)){
		if ((SSPX->SR & SSP_SR_TNF) && (dlen>0)){
			// Write data to buffer		
			SSP_SendData(SSPX, *wdata8);
			wdata8++;
			dlen--;
		}
		// Check for any data available in RX FIFO
		while ((SSPX->SR & SSP_SR_RNE)){
			// Read data from SSP data
			SSP_ReceiveData(SSPX);				
			rlen--;
		}
	}	
}

